<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>表单字段管理</title>
<jsp:include page="../inc.jsp"></jsp:include>
	<script type="text/javascript"
	src="${pageContext.request.contextPath}/plug-in/custom/form.js"
	charset="utf-8"></script>
<script type="text/javascript">
	Ext.onReady(function(){
		Ext.QuickTips.init();
		createGrid();
		createLayout();
		createForm();
		form = Ext.create('userForm');
        grid.store.load();
	});
	
	var gridEl = 'repTime-grid';
	var grid, form, selModel, toolbar, searchFlds;
	var win;
	
	function createGrid(){
		searchFlds = new Ext.util.MixedCollection();
		var fldTimeName = new Ext.form.TextField({
			name : 'fieldDisplayName',
			id : gridEl + '-name',
			fieldLabel : '显示名称',
			allowBlank : true,
			width : 200
		});

		searchFlds.add('fieldDisplayName', fldTimeName);
		grid =	Ext.create('gridView',{
			remoteSort : true,
			gridId : gridEl,
            dataAutoLoad:false,
			checkboxSelectionModel:true,
			searchFlds : searchFlds,
			entityClassName : 'com.rover.system.entity.FormTableField',
			queryUrl : 'formTableFieldController/query.action',
			deleteUrl : 'formTableFieldController/delete.action',
			recordPk : [ "fieldId",'fieldName' ]

		});
        grid.getStore().on('beforeload', function(store, options) {
            store.proxy.extraParams.tableId='<%=request.getParameter("tableId")%>';
        }, this, true);
	}

	// 刷新列表
	function reloadRecords() {
		grid.getStore().reload();
	}

	function createWindows() {
		if (win == null) {
			win = new Ext.Window({
				title : '新增',
				iconCls : 'icon-win',
				autoHeight : true,
				width : 510,
				height : 350,
				buttonAlign : 'center',
				buttons : [ {
					text : "保存",
					handler : function() {
						if (form.getForm().isValid()) {
							form.getForm().submit({
								url : getRootPath()+'/formTableFieldController/save.action',
                                params:{tableId:'<%=request.getParameter("tableId")%>'},
								scope : form,
								success : function(form, action) {
									win.hide();
									grid.getStore().reload();
								},
								failure : function(form, action) {
									 if (action.result.message == undefined)
									      Ext.Msg.alert('错误', '网络连接失败.');
									    else
									      Ext.Msg.alert('错误', action.result.message);
								},
								waitMsg : '保存数据...'
							});
						} else {
							Ext.Msg.alert('提示', '表单含有无效或空数据');
						}
					},
					id : "btnSave"
				}, {
					text : "关闭",
					id : "btnClose",
					handler : function() {
						win.hide();
					}
				} ],
				layout : 'fit',
				plain : false,
				closable : false,
				modal : true,
				items : [ form ]
			});
		}
		win.show();
	}
	
	// 创建form表单
	function createForm() {
		Ext.define('userForm', {
			extend : 'Ext.form.Panel',
			fields : new Ext.util.MixedCollection(),
			initComponent : function() {
				var me = this;
				var tn = 1;

				this.fields.add('fieldId', new Ext.form.Hidden({
					name : 'fieldId',
					dataIndex : "fieldId"
				}));
			
				this.fields.add("fieldDisplayName", new Ext.form.TextField({
					name : "fieldDisplayName",
					dataIndex : "fieldDisplayName",
					fieldLabel : "显示名称",
					allowBlank : false
				}));
				this.fields.add("fieldName", new Ext.form.TextField({
					name : "fieldName",
					dataIndex : "fieldName",
					fieldLabel : "列名",
					allowBlank : false
				}));


                // Simple ComboBox using the data store
                this.fields.add("fieldType", Ext.create('Ext.form.field.ComboBox', {
                    fieldLabel: '字段类型',
                    allowBlank : false,
                    displayField: 'itemText',
                    valueField:'itemValue',
                    name:'fieldType',
                    store: Ext.create('Ext.data.Store', {
                        fields: [
                             'itemText','itemValue'
                        ],
                        data: [
                            { "itemText": "日期类型(date)",'itemValue':'Date' } ,
                            { "itemText": "数字类型(Decimal)",'itemValue':'Decimal' } ,
                            { "itemText": "整数(Integer)",'itemValue':'Integer' },
                            { "itemText": "字符串(String)",'itemValue':'String' },
                            { "itemText": "文本(Text)",'itemValue':'Text' },
                            { "itemText": "二进制流(Image)",'itemValue':'Image' }
                        ]
                    }),
                    queryMode: 'local',
                    typeAhead: true  ,
                    listeners:{
                        select : function(combo, record,index){
                            var     oracleSequence=form.getForm().findField('decimalPlaces');
                                switch (combo.value){
                                    case"Decimal":
                                             oracleSequence.setReadOnly(false);
                                        break ;
                                    default:
                                        oracleSequence.setReadOnly(true);
                                        break;
                                }
                            var controlType=  form.getForm().findField('controlType');
                            controlType.clearValue();
                            //过滤数据源
                            controlType.getStore().clearFilter();
                            //找出包含此项的数据
                            controlType.getStore().filterBy(function (item) {
                                return (item.get("fieldType").indexOf(combo.value)>-1 || item.get("fieldType")==combo.value);
                            });
                        }
                    }
                }));
                this.fields.add("decimalPlaces", new Ext.form.NumberField({
                    name : "decimalPlaces",
                    width:100,
                    labelWidth:50,
                    readOnly:true,
                    dataIndex : "decimalPlaces",
                    fieldLabel : "小数位"
                }));
                this.fields.add("fieldLength", new Ext.form.NumberField({
                    name : "fieldLength",
                    dataIndex : "fieldLength",
                    labelWidth:80,
                     value:50,
                    minValue:0,
                    width:140,
                    fieldLabel : "字段长度"
                }));
                this.fields.add("controlType", Ext.create('Ext.form.field.ComboBox', {
                    fieldLabel: '控件类型',
                    allowBlank : false,
                    displayField: 'itemText',
                    valueField:'itemValue',
                    name:'controlType',
                    store: Ext.create('Ext.data.Store', {
                        type:'array',
                        fields: [
                            'itemText','itemValue' ,'fieldType'
                        ],
                        data: [
                            { itemText: "日期选择项",itemValue:'datefield',fieldType:'Date' } ,
                            { itemText: "隐藏域",itemValue:'hidden',fieldType:'StringTextDateDecimalInteger' } ,
                            { itemText: "数字编辑器",itemValue:'numberfield',fieldType:'DecimalInteger' },
                            { itemText: "多行文本框",itemValue:'textarea',fieldType:'StringText' },
                            { itemText: "文本框",itemValue:'textfield',fieldType:'StringText' },
                            { itemText: "文件上传",itemValue:'file',fieldType:'Image' }
                        ]
                    }),
                    queryMode: 'local',
                    typeAhead: true ,
                    forceSelection: true
                }));
                this.fields.add("codeName",new comboBox({
                    name : "codeName",
                    dataIndex : "codeName",
                    fieldLabel : "代码表",
                    labelAlign : "right",
                    dataUrl:"codeController/getList.action",
                    dataFields : ['id', 'name'],
                    queryMode: 'local',
                    typeAhead : false,
                    forceSelection : true,
                    loadingText : '正在搜索...',
                    hideTrigger : false ,
                    allowBlank : true
                }));
                this.fields.add("mustFill",new Ext.form.RadioGroup ({
                    dataIndex : "mustFill",
                    layout: "column",
                    fieldLabel : "必填",
                    allowBlank : false,
                    width:250,
                    border: false,
                    name: "mustFill",
                    id: "mustFill",
                    items:[{
                        boxLabel: "是",
                        name: "mustFill",
                        inputValue: "1"
                    },{
                        boxLabel: "否",
                        name: "mustFill",
                        inputValue: "0",
                        checked: true
                    }]
                }));

                this.fields.add("isForeignKey",new Ext.form.RadioGroup ({
                    dataIndex : "isForeignKey",
                    layout: "column",
                    fieldLabel : "唯一字段",
                    width:250,
                    allowBlank : false,
                    border: false,
                    name: "isForeignKey",
                    items:[{
                        boxLabel: "是",
                        name: "isForeignKey",
                        inputValue: "1"
                    },{
                        boxLabel: "否",
                        name: "isForeignKey",
                        inputValue: "0",
                        checked: true
                    }]
                }));

                this.fields.add("dispInFrom",new Ext.form.RadioGroup ({
                    dataIndex : "dispInFrom",
                    layout: "column",
                    fieldLabel : "表单显示",
                    allowBlank : false,
                    width:250,
                    border: false,
                    name: "dispInFrom",
                    items:[{
                        boxLabel: "是",
                        name: "dispInFrom",
                        inputValue: "1" ,
                        checked: true
                    },{
                        boxLabel: "否",
                        name: "dispInFrom",
                        inputValue: "0"
                    }]
                }));
                this.fields.add("dispInGrid",new Ext.form.RadioGroup ({
                    dataIndex : "dispInGrid",
                    layout: "column",
                    fieldLabel : "列表显示",
                    allowBlank : false,
                    width:250,
                    border: false,
                    name: "dispInGrid",
                    items:[{
                        boxLabel: "是",
                        name: "dispInGrid",
                        inputValue: "1",
                        checked: true
                    },{
                        boxLabel: "否",
                        name: "dispInGrid",
                        inputValue: "0"
                    }]
                }));


                this.fields.add("colspan",new Ext.form.RadioGroup ({
                    dataIndex : "colspan",
                    layout: "column",
                    fieldLabel : "显示宽度",
                    width:250,
                    allowBlank : false,
                    border: false,
                    name: "colspan",
                    items:[{
                        boxLabel: "双倍",
                        name: "colspan",
                        inputValue: "1"
                    },{
                        boxLabel: "单倍",
                        name: "colspan",
                        inputValue: "0",
                        checked: true
                    }]
                }));
                this.fields.add("dispQuery",new Ext.form.RadioGroup ({
                    dataIndex : "dispQuery",
                    layout: "column",
                    fieldLabel : "是否查询",
                    width:250,
                    allowBlank : false,
                    border: false,
                    name: "dispQuery",
                    items:[{
                        boxLabel: "是",
                        name: "dispQuery",
                        inputValue: "1"
                    },{
                        boxLabel: "否",
                        name: "dispQuery",
                        inputValue: "0",
                        checked: true
                    }]
                }));

				this.fields.add("sortSQ", new Ext.form.NumberField({
					name : "sortSQ",
					dataIndex : "sortSQ",
					fieldLabel : "显示顺序"
				}));
			
				this.items = [  this.fields.get("fieldId"),
                        {
                            xtype: 'container',
                            layout: 'hbox',
                            margin: '0 0 5 0',
                            items: [ this.fields.get("fieldDisplayName"),this.fields.get("fieldName")]},
                    {
                        xtype: 'container',
                        margin: '0 0 5 0',
                        layout: 'hbox',
                        items: [ this.fields.get("fieldType"),this.fields.get("fieldLength"), this.fields.get("decimalPlaces")]},
                    {
                        xtype: 'container',
                        margin: '0 0 5 0',
                        layout: 'hbox',
                        items: [this.fields.get("isForeignKey")]},
                    {
                        xtype: 'container',
                        margin: '0 0 5 0',
                        layout: 'hbox',
                        items: [ this.fields.get("controlType"),this.fields.get("codeName")]},
                    {
                        xtype: 'container',
                        margin: '0 0 5 0',
                        layout: 'hbox',
                        items: [ this.fields.get("mustFill"),this.fields.get("dispInFrom")]},
                    {
                        xtype: 'container',
                        margin: '0 0 5 0',
                        layout: 'hbox',
                        items: [ this.fields.get("dispInGrid"),this.fields.get("colspan")]},
                    {
                        xtype: 'container',
                        margin: '0 0 5 0',
                        layout: 'hbox',
                        items: [ this.fields.get("dispQuery"),this.fields.get("sortSQ")]}

				 ];
                this.xtype= 'form';
				this.frame = false;
				this.border = true;
				this.split = true;
                this.bodyBorder= true;
                        this.fieldDefaults= {
                          labelWidth: 75,
                            labelAlign:'right',
                            msgTarget: 'side'
                };
                this.defaults={
                    anchor: '100%'
                };
				this.callParent(arguments);
			},
			onRender : function() {
				this.callParent(arguments);
			},
			newDataRecord : function() {
				this.getForm().reset();
			}
		});
	}

	// 新建或修改表单成功提交后,重新加载其父节点
	function afterCommitFormSuccess(operation, recordData) {
		onWinHide();
		grid.getStore().reload();
	}
	
	// 创建新的记录，初始化表单
	function EditRecord() {
		var sm = grid.getSelectionModel();
		var records = sm.getSelection();
		
		if (records.length <= 0) {
			Ext.Msg.alert('错误', "未选中记录，不能修改！");
			return;
		}
		var data = records[0].data;
        form.getForm().loadRecord( records[0]);
        var controlType=  form.getForm().findField('controlType');
        controlType.clearValue();
        //过滤数据源
        controlType.getStore().clearFilter();
        //找出包含此项的数据
        controlType.getStore().filterBy(function (item) {
            return (item.get("fieldType").indexOf(form.getForm().findField("fieldType").getValue())>-1 || item.get("fieldType")==form.getForm().findField("fieldType").getValue());
        });
        controlType.setValue(data.controlType);
		createWindows();

	}
	

	// 创建layout
	function createLayout() {
		toolbar = new Ext.Toolbar({
            enableOverflow : true,
			items : [ {
				text : "新增",
				iconCls : 'addIcon',
				id : "tlb_NEW",
				handler : function() {
					form.newDataRecord();
					createWindows();
                    win.setTitle('新增');

				}
			}, '-', {
				text : "编辑",
				iconCls : 'editIcon',
				id : "tlb_EDIT",
				handler : function() {
					EditRecord();
                    win.setTitle('编辑');
				}
			}, '-', {
				text : "删除",
				iconCls : 'deleteIcon',
				id : "tlb_DELETE",
				handler : function() {
					grid.deleteRecord();
				}
			}, "->",  searchFlds.get("fieldDisplayName"), {
		        text: "搜索",
		        iconCls : 'searchIcon',
		        handler: function () {
		        	grid.load();
		        }
		    } ]
		});

		var viewport = new Ext.Viewport({
			layout : 'border',
			items : [ {
				layout : 'fit',
				region : 'north',
				border : false,
				items : [ toolbar ]
			}, {
				layout : 'border',
				region : 'center',
				border : false,
				items : [ grid ]
			} ]
		});

		viewport.doLayout();
	}

</script>
</head>
<body>
</body>
</html>